package cn.ecpay.unionpay.settle.notify;

import cn.ecpay.unionpay.settle.Common.UnionpayDict;
import cn.ecpay.unionpay.settle.util.LogUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 通知接口
 * Created by zhaoyanzeng on 2018/11/26.
 */
@Component
public class NotifyReceiver {

    Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private LaiZhangNotify laiZhangNotify;
    @Resource
    private TuiHuiNotify tuiHuiNotify;
    @Resource
    private QuotaIncreaseNotify quotaIncreaseNotify;
    @Resource
    private SingleFundSettlementNotify singleFundSettlementNotify;
    @Resource
    private SingleQueryNotify singleQueryNotify;
    @Resource
    private ReturnMoneyNotify returnMoneyNotify;
    @RabbitListener(queues = "unionpay-forwarding-notify")
    public void process(String msg) throws Exception {
        LogUtil.writeLog("收到通知报文：" + msg);
        Map<String, String> msgMap =  getAllRequestParamStream(msg);
        String txnType = msgMap.get("txnType");
        if(StringUtils.isEmpty(txnType)){
            //TODO
            LogUtil.writeLog("交易类型不能为空");
            return;
        }
        if(UnionpayDict.TXN_TYPE_LAIZHANG.equals(txnType.trim())){
            laiZhangNotify.LaiZhangNotify(msgMap);
        }else if(UnionpayDict.TXN_TYPE_TUIHUI.equals(txnType.trim())){
            tuiHuiNotify.tuiHuiNotify(msgMap);
        }else if(UnionpayDict.TXN_TYPE_SINGLEFUNDSETTLEMENT.equals(txnType.trim())){
            singleFundSettlementNotify.singleFundSettlement(msgMap);
        }else if(UnionpayDict.TXN_TYPE_SINGLEQUERY.equals(txnType.trim())){
            singleQueryNotify.singleQuery(msgMap);
        }else if(UnionpayDict.TXN_TYPE_QUOTAINCREASE.equals(txnType.trim())){
            quotaIncreaseNotify.quotaIncrease(msgMap);
        }else if(UnionpayDict.TXN_TYPE_RETURNMONEY.equals(txnType.trim())){
            returnMoneyNotify.returnMoney(msgMap);
        }
    }

    /**
     * 获取请求参数中所有的信息。
     *
     * @param notifyStr 通知内容
     * @return
     */
    private Map<String, String> getAllRequestParamStream(String notifyStr) {
        Map<String, String> res = new HashMap<String, String>();
        try {
            JSONObject jObj = JSONObject.fromObject(notifyStr);
            for (Iterator<String> iter = jObj.keys(); iter.hasNext(); ) {
                String key = iter.next();
                String value = jObj.getString(key);
                res.put(key, value);
            }
        }catch (Exception e){
            LogUtil.writeLog("报文处理错误：" +e.getMessage() );
            e.printStackTrace();
        }
        return res;
    }
}
